'''
Created on 20 juil. 2011

@author: nathanael
'''

import re
from lxml import etree

from pybible.core.html.style import Style

class Viewer(object):
    def __init__(self, style=Style()):
        
        self.style = style
        
        self.html = etree.Element('html')
        head = etree.Element('head')
        self.html.append(head)
        head.append(self.style.get_element())
        body = etree.Element('body')
        self.html.append(body)
        self.body = body

    def new_paragraph(self):
        self.paragraph = etree.Element('p')
        self.body.append(self.paragraph)
        return self.paragraph
    
    @staticmethod
    def new_regex_group(div, txt, regex):
        ""
        i = 0
        tag = None
        pattern = re.compile(regex)
        for match in pattern.finditer(txt):
            if tag is None:
                div.text = txt[i:match.start(0)]
            else:
                tag.tail = txt[i:match.start(0)]
            new_tag = etree.Element('strong', {'class':'match'})
            new_tag.text = match.group(0)
            div.append(new_tag)
            i = match.end(0)
            tag = new_tag
            
        if i == 0:
            tag.tail = txt
        else:
            if i < len(txt):
                tag.tail = txt[i:]
        

    def __str__(self):
        s = self.tostring()
        return s
    
    def tostring(self):
        return etree.tostring(self.html,
                              pretty_print=True,
                              xml_declaration=True,
                              encoding='utf-8',
                              method='xml')
